#!/usr/bin/env python
#-*- coding:UTF-8 -*-
#####################################################
# Author: Jiaion - jiaion21@gmail.com
# Last modified:  2011-04-23 15:39
# Filename:  Sendmail.py
#####################################################

import smtplib
import sys
from optparse import OptionParser
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from os.path import abspath, dirname, join
sys.path.insert(0, abspath(join(dirname(__file__), "../")))

import Jredis as redis

def send_mail(mail_user,mail_pass,mail_server,to_list,Mail):
  '''
  to_list: send object
  sub: subject
  msg: content
  send_mail("jiaion@163.com","sub","msg")
  '''
  MIMEText._charset = 'utf-8' 
  i, j, k = mail_server.split(".")
  mail_postfix = j+"."+k
  from_mail = mail_user + "<" + mail_user + "@" + mail_postfix + ">"
  mail_user = mail_user + "@" + mail_postfix
  data = MIMEMultipart('alternative')
  HtmlMsg = MIMEText(Mail,'html',_charset='utf-8')
  TextMsg = MIMEText('Text','plain',_charset='utf-8')
  data.attach(HtmlMsg)
  sub = 'Socket防火墙'
  data['Subject'] = sub
  data['From'] = from_mail
  data['To'] = ";".join(to_list)
  print data
  try:
    s = smtplib.SMTP()
    s.connect(mail_server)
    s.login(mail_user, mail_pass)
    s.sendmail(from_mail, to_list, data.as_string())
    s.quit()
    return True
  except Exception, e:
    print str(e)
    return False

def argument(Print='No'):
  parser = OptionParser(usage="%prog -s smtp.163.com -u username -p password -o -m -t ",version="%prog Jiaion 1.0")
  parser.add_option("-s", dest="mailsvr", action="store", help="Mail server address smtp.163.com")
  parser.add_option("-u", dest="username", action="store", help="You mail username")
  parser.add_option("-p", dest="passwd", action="store", help="You mail password")
  parser.add_option("-o", dest="object", action="store", help="You mail subject")
  parser.add_option("-m", dest="msg", action="store", help="You mail content")
  parser.add_option("-t", dest="to", action="store", help="Sendmail to address \"jiaion@163.com,jiaion@139.com\" ")

  (options, args) = parser.parse_args()
  ARGDIR = vars(options)
  if Print == "Yes" : parser.print_help()
  return ARGDIR

if __name__ == '__main__':
  if len(sys.argv[1:]) >= 1:
    argdir = argument()
    Work = redis.lpops('USERREG')
    try :
      if Work.get('Type') == 'SendUser':
        msg = Work.get('Mail').encode('utf-8') + Work.get('Pass').encode('utf-8')
        mailadd_list = [ Work.get('User') + u'@rekoo.com' ]
      else :
        msg = Work.get('Mail').encode('utf-8')
        mailadd_list = Work.get('ToList')
    except AttributeError:
      sys.exit(1)
    mail_server = argdir["mailsvr"]
    mail_user = argdir["username"]
    mail_pass = argdir["passwd"]
    if send_mail(mail_user,mail_pass,mail_server,mailadd_list,msg):
      print "发送成功"
    else:
      print "发送失败"
  else:
    argument(Print="Yes")
    sys.exit(1)
